<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>调整航班</title>
  <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
  <link rel="stylesheet" href="css/adjustFlights.css">
</head>
<body>
<%@ include file="adminNavbar.jsp" %>

<div class="container mx-auto p-4 mt-16">
  <!-- 按钮组 -->
  <div class="flex justify-between items-center mb-6">
    <h1 class="text-3xl font-bold text-gray-800">调整航班</h1>
    <div class="flex gap-2">
      <button id="showWithAirline" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">有席别航班</button>
      <button id="showWithoutAirline" class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600">无席别航班</button>
    </div>
    <button id="addBtn" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">+ 添加</button>
    <button id="deleteBtn" class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600">- 删除</button>
    <button id="modifyBtn" class="px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600">🖊 修改</button>
  </div>

  <!-- 航班数据表格 -->
  <div class="overflow-x-auto">
    <table class="min-w-full divide-y divide-gray-200" id="flightTable">
      <thead class="bg-gray-50">
      <tr>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">序号</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">航班ID</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">起飞时间</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">到达时间</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">起飞站</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">到达站</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">登机时间</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">舱位</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">剩余票数</th>
      </tr>
      </thead>
      <tbody class="bg-white divide-y divide-gray-200" id="flightTableBody">
      <!-- 数据将通过JavaScript动态填充 -->
      </tbody>
    </table>
  </div>

  <!-- 分页控件 -->
  <div class="mt-4 flex justify-end items-center">
    <span class="mr-2">当前页数：</span>
    <input type="number" id="currentPage" value="1" min="1" class="w-16 px-2 py-1 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400">
    <span class="mx-2">/</span>
    <span id="totalPages">1</span>
    <button id="goToPage" class="ml-4 px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600">跳转</button>
  </div>

  <!-- 背景灰幕 -->
  <div class="modal-backdrop" id="modalBackdrop"></div>
</div>

<!-- 添加航班弹窗 -->
<div class="add-modal" id="addFlightModal">
  <h2 class="text-2xl font-bold mb-4">添加新航班</h2>
  <form id="addFlightForm" action="FlightAdjustmentServlet" method="post">
    <input type="hidden" name="operation" value="addFlight">
    <div class="mb-4">
      <label class="block text-gray-700 font-semibold mb-2">起飞时间</label>
      <input type="datetime-local" name="starttime" class="w-full px-4 py-2 border rounded-lg" required>
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-semibold mb-2">到达时间</label>
      <input type="datetime-local" name="endtime" class="w-full px-4 py-2 border rounded-lg" required>
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-semibold mb-2">起飞站</label>
      <input type="text" name="takeoffstation" class="w-full px-4 py-2 border rounded-lg" required>
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-semibold mb-2">到达站</label>
      <input type="text" name="arrivalstation" class="w-full px-4 py-2 border rounded-lg" required>
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-semibold mb-2">登机时间</label>
      <input type="datetime-local" name="boardingtime" class="w-full px-4 py-2 border rounded-lg" required>
    </div>
    <button type="submit" class="w-full btn-submit">提交</button>
  </form>
</div>

<!-- 添加席别弹窗 -->
<div class="add-modal" id="addAirlineModal">
  <h2 class="text-2xl font-bold mb-4">添加新席别</h2>
  <form id="addAirlineForm" action="FlightAdjustmentServlet" method="post">
    <input type="hidden" name="operation" value="addAirline">
    <input type="hidden" name="fid" id="selectedFid">
    <div class="mb-4">
      <label class="block text-gray-700 font-semibold mb-2">舱位（席别）</label>
      <input type="text" name="position" class="w-full px-4 py-2 border rounded-lg" required>
    </div>
    <div class="mb-4">
      <label class="block text-gray-700 font-semibold mb-2">剩余票数</label>
      <input type="number" name="remain" class="w-full px-4 py-2 border rounded-lg" required>
    </div>
    <button type="submit" class="w-full btn-submit">提交</button>
  </form>
</div>


<!-- 删除席别/航班弹窗 -->
<div class="add-modal" id="deleteModal">
  <h2 class="text-2xl font-bold mb-4" id="deleteTitle">删除确认</h2>
  <form id="deleteForm" action="FlightAdjustmentServlet" method="post">
    <input type="hidden" name="operation" id="deleteOperation">
    <input type="hidden" name="fid" id="deleteFid">
    <input type="hidden" name="aid" id="deleteAid">
    <div class="mb-4" id="selectPositionDiv" style="display: none;">
      <label class="block text-gray-700 font-semibold mb-2">选择要删除的席别</label>
      <select name="position" id="positionSelect" class="w-full px-4 py-2 border rounded-lg">
        <!-- 动态填充席别选项 -->
      </select>
    </div>
    <button type="submit" class="w-full bg-red-500 text-white py-2 rounded-lg">确认删除</button>
  </form>
</div>

<!-- 修改航班/席别弹窗 -->
<div class="add-modal" id="modifyModal">
  <h2 class="text-2xl font-bold mb-4">修改航班信息</h2>
  <form id="modifyForm" action="FlightAdjustmentServlet" method="post">
    <input type="hidden" name="operation" id="modifyOperation">
    <input type="hidden" name="fid" id="modifyFid">
    <input type="hidden" name="aid" id="modifyAid">

    <!-- 修改类型选择 -->
    <div class="mb-4">
      <label class="block text-gray-700 font-semibold mb-2">修改类型</label>
      <div class="flex gap-4">
        <label class="flex items-center">
          <input type="radio" name="modifyType" value="flight" class="mr-2" checked> 航班
        </label>
        <label class="flex items-center">
          <input type="radio" name="modifyType" value="airline" class="mr-2" id="airlineRadio"> 席别
        </label>
      </div>
    </div>

    <!-- 修改字段选择 -->
    <div class="mb-4" id="fieldSelectDiv">
      <label class="block text-gray-700 font-semibold mb-2">选择修改字段</label>
      <select id="fieldSelect" name="field" class="w-full px-4 py-2 border rounded-lg">
        <option value="starttime">起飞时间</option>
        <option value="endtime">到达时间</option>
        <option value="takeoffstation">起飞站</option>
        <option value="arrivalstation">到达站</option>
        <option value="boardingtime">登机时间</option>
      </select>
    </div>

    <!-- 修改值输入 -->
    <div class="mb-4" id="valueInputDiv">
      <label class="block text-gray-700 font-semibold mb-2" id="valueLabel">新值</label>
      <input type="text" id="valueInput" name="newValue" class="w-full px-4 py-2 border rounded-lg" required>
    </div>

    <button type="submit" class="w-full bg-green-500 text-white py-2 rounded-lg">确认修改</button>
  </form>
</div>

<script>
  let selectedFlight = null; // 记录选中的航班ID
  let selectedFlightData = null;
  let currentView = 'withAirline';  // 记录当前视图状态

  // 加载航班数据（类似flightSearch.jsp的逻辑）
  function loadFlights(page = 1) {
    const url = `getFlights?page=` + page;
    fetch(url)
            .then(res => res.json())
            .then(data => {
              const tbody = document.getElementById('flightTableBody');
              tbody.innerHTML = '';
              data.flights.forEach((flight, index) => {
                const row = document.createElement('tr');
                // 添加序号列（当前页内从1开始递增）
                const serialCell = document.createElement('td');
                serialCell.textContent = index + 1;
                row.appendChild(serialCell);

                row.innerHTML += `
                    <td class="px-6 py-4">` + flight.fid + `</td>
                    <td class="px-6 py-4">` + flight.starttime + `</td>
                    <td class="px-6 py-4">` + flight.endtime + `</td>
                    <td class="px-6 py-4">` + flight.takeoffstation + `</td>
                    <td class="px-6 py-4">` + flight.arrivalstation + `</td>
                    <td class="px-6 py-4">` + flight.boardingtime + `</td>
                    <td class="px-6 py-4">` + flight.position + `</td>
                    <td class="px-6 py-4">` + flight.remain + `</td>
                  `;
                row.addEventListener('click', () => {
                  if (row.classList.contains('selected-row')) {
                    // 已选中时点击取消选中
                    row.classList.remove('selected-row');
                    selectedFlight = null;
                    selectedFlightData = null;
                  } else {
                    // 未选中时先清除其他行选中状态
                    document.querySelectorAll('#flightTableBody tr').forEach(tr => {
                      tr.classList.remove('selected-row');
                    });
                    // 选中当前行
                    row.classList.add('selected-row');
                    selectedFlight = flight.fid;
                    selectedFlightData = flight;
                  }
                });
                tbody.appendChild(row);
              });
              document.getElementById('totalPages').textContent = data.totalPages;
            });
  }

  // 加载无席别航班
  function loadFlightsWithoutAirline(page = 1) {
    const url = `FlightAdjustmentServlet?operation=getFlightsWithoutAirline&page=` + page;
    fetch(url)
            .then(res => res.json())
            .then(data => {
              const tbody = document.getElementById('flightTableBody');
              tbody.innerHTML = '';
              data.flights.forEach((flight, index) => {
                const row = document.createElement('tr');
                const serialCell = document.createElement('td');
                serialCell.textContent = index + 1;
                row.appendChild(serialCell);
                row.innerHTML += `
                    <td class="px-6 py-4">` + flight.fid + `</td>
                    <td class="px-6 py-4">` + flight.starttime + `</td>
                    <td class="px-6 py-4">` + flight.endtime + `</td>
                    <td class="px-6 py-4">` + flight.takeoffstation + `}</td>
                    <td class="px-6 py-4">` + flight.arrivalstation + `</td>
                    <td class="px-6 py-4">` + flight.boardingtime + `</td>
                    <td class="px-6 py-4">无</td>  <!-- 无席别时显示"无" -->
                    <td class="px-6 py-4">0</td>   <!-- 剩余票数为0 -->
                `;
                row.addEventListener('click', () => {
                  selectedFlightData = flight;  // 记录选中的航班数据
                  if (row.classList.contains('selected-row')) {
                    // 已选中时点击取消选中
                    row.classList.remove('selected-row');
                    selectedFlight = null;
                    selectedFlightData = null;
                  } else {
                    // 未选中时先清除其他行选中状态
                    document.querySelectorAll('#flightTableBody tr').forEach(tr => {
                      tr.classList.remove('selected-row');
                    });
                    // 选中当前行
                    row.classList.add('selected-row');
                    selectedFlight = flight.fid;
                    selectedFlightData = flight;
                  }
                });
                tbody.appendChild(row);
              });
              document.getElementById('totalPages').textContent = data.totalPages;
            });
  }

  // 切换视图按钮事件
  document.getElementById('showWithAirline').addEventListener('click', () => {
    currentView = 'withAirline';
    loadFlights();
  });

  document.getElementById('showWithoutAirline').addEventListener('click', () => {
    currentView = 'withoutAirline';
    loadFlightsWithoutAirline();
  });

  // 初始化加载数据
  loadFlights();

  // 添加按钮点击事件
  document.getElementById('addBtn').addEventListener('click', () => {
    if (!selectedFlightData && currentView === 'withoutAirline') {
      alert('请选择一个航班');
      return;
    }
    if (currentView === 'withoutAirline') {
        // 无席别视图下，显示添加席别弹窗
        document.getElementById('addAirlineModal').style.display = 'block';
        document.getElementById('selectedFid').value = selectedFlightData.fid;  // 传递航班ID到隐藏域
    } else {
    if (selectedFlight) {
      document.getElementById('selectedFid').value = selectedFlight;
      document.getElementById('addAirlineModal').style.display = 'block';
    } else {
      document.getElementById('addFlightModal').style.display = 'block';
    }
  }
  document.getElementById('modalBackdrop').style.display = 'block';
  });

  // 提交添加表单（保持原有逻辑不变）
  document.getElementById('addFlightForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const response = await fetch('FlightAdjustmentServlet', { method: 'POST', body: formData });
    const result = await response.text();
    if (result === 'success') {
      alert('添加成功');
      document.getElementById('deleteModal').style.display = 'none';
      loadFlights(); // 刷新数据
    } else {
      alert('添加失败');
    }
  });

  // 提交添加表单
  document.getElementById('addAirlineForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const response = await fetch('FlightAdjustmentServlet', { method: 'POST', body: formData });
    const result = await response.text();
    if (result === 'success') {
      alert('添加成功');
      document.getElementById('addAirlineModal').style.display = 'none';
      loadFlights(); // 刷新数据
    } else {
      alert('添加失败');
    }
  });

  // 删除按钮点击事件
  document.getElementById('deleteBtn').addEventListener('click', async () => {
    if (!selectedFlight) {
      alert('请选择一个航班');
      return;
    }

    // 获取该航班的席别列表
    const response = await fetch(`getAirlineByFid?fid=` + selectedFlight + ``);
    const airlines = await response.json();

    if (airlines.length === 0) {
      // 无席别，直接删除航班
      if (confirm('该航班无席别，确认删除航班？')) {
        const formData = new FormData();
        formData.append('operation', 'deleteFlight');
        formData.append('fid', selectedFlight);
        await fetch('FlightAdjustmentServlet', { method: 'POST', body: formData });
        loadFlights(); // 刷新数据
      }
    } else {
      // 有席别，显示删除弹窗
      const deleteModal = document.getElementById('deleteModal');
      const positionSelect = document.getElementById('positionSelect');
      positionSelect.innerHTML = airlines.map(airline =>
              `<option value=` + airline.aid + `>` + airline.position + `</option>`
      ).join('');

      document.getElementById('deleteTitle').textContent = airlines.length > 1
              ? '选择要删除的席别'
              : '确认删除该席别？';
      document.getElementById('selectPositionDiv').style.display = airlines.length > 1 ? 'block' : 'none';
      document.getElementById('deleteFid').value = selectedFlight;
      document.getElementById('deleteOperation').value = 'deleteAirline';
      deleteModal.style.display = 'block';
      document.getElementById('modalBackdrop').style.display = 'block'; // 显示灰幕
    }
  });

  // 提交删除表单
  document.getElementById('deleteForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const positionSelect = document.getElementById('positionSelect');
    // 获取选中的席别aid（来自option的value）
    const selectedAid = positionSelect.value;
    document.getElementById('deleteAid').value = selectedAid; 
    const formData = new FormData(e.target);
    formData.append('aid', selectedAid); // 关键修改：添加aid参数
    const response = await fetch('FlightAdjustmentServlet', { method: 'POST', body: formData });
    const result = await response.text();
    if (result === 'success') {
      alert('删除成功');
      document.getElementById('deleteModal').style.display = 'none';
      loadFlights(); // 刷新数据
    } else {
      alert('删除失败');
    }
  });

  // 修改按钮点击事件
  document.getElementById('modifyBtn').addEventListener('click', async () => {
    if (!selectedFlightData) {
      alert('请选择一个航班');
      return;
    }

    // 显示修改弹窗
    document.getElementById('modifyModal').style.display = 'block';
    document.getElementById('modalBackdrop').style.display = 'block'; // 显示灰幕
    document.getElementById('modifyFid').value = selectedFlightData.fid;
    document.getElementById('modifyOperation').value = currentView === 'withAirline' ? 'modifyAirline' : 'modifyFlight';  // 根据视图调整操作类型
    
    // 无席别视图下，禁用席别修改选项
    if (currentView === 'withoutAirline') {
        document.getElementById('airlineRadio').disabled = true;
        document.querySelector('input[value="flight"]').checked = true;
        updateFieldOptions('flight');  // 只显示航班字段
    } else {
        document.getElementById('airlineRadio').disabled = false;
    }

    // 查询该航班是否有席别
    const airlineResponse = await fetch(`getAirlineByFid?fid=` + selectedFlightData.fid);
    const airlines = await airlineResponse.json();

    // 禁用/启用席别单选框
    const airlineRadio = document.getElementById('airlineRadio');
    airlineRadio.disabled = airlines.length === 0;
    if (airlines.length === 0) {
      airlineRadio.checked = false;
      document.querySelector('input[value="flight"]').checked = true;
    }

    // 初始化字段选择（航班默认字段）
    updateFieldOptions('flight');
  });

  // 更新字段选择下拉列表
  function updateFieldOptions(type) {
    const fieldSelect = document.getElementById('fieldSelect');
    const valueInput = document.getElementById('valueInput');
    fieldSelect.innerHTML = '';

    if (type === 'flight') {
      // 航班字段选项
      const fields = ['starttime', 'endtime', 'takeoffstation', 'arrivalstation', 'boardingtime'];
      fields.forEach(field => {
        const option = document.createElement('option');
        option.value = field;
        option.textContent = field === 'starttime' ? '起飞时间' :
                field === 'endtime' ? '到达时间' :
                        field === 'takeoffstation' ? '起飞站' :
                                field === 'arrivalstation' ? '到达站' : '登机时间';
        fieldSelect.appendChild(option);
      });
      // 设置输入框类型（日期时间字段显示datetime-local）
      const currentField = fieldSelect.value;
      valueInput.type = ['starttime', 'endtime', 'boardingtime'].includes(currentField) ? 'datetime-local' : 'text';
    } else {
      // 席别字段选项
      const fields = ['position', 'remain'];
      fields.forEach(field => {
        const option = document.createElement('option');
        option.value = field;
        option.textContent = field === 'position' ? '舱位（席别）' : '剩余票数';
        fieldSelect.appendChild(option);
      });
      valueInput.type = field === 'remain' ? 'number' : 'text';
    }
  }

  // 提交修改表单
  document.getElementById('modifyForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const modifyType = document.querySelector('input[name="modifyType"]:checked').value;

    // 设置操作类型
    formData.set('operation', modifyType === 'flight' ? 'modifyFlight' : 'modifyAirline');

    const response = await fetch('FlightAdjustmentServlet', { method: 'POST', body: formData });
    const result = await response.text();
    if (result === 'success') {
      alert('修改成功');
      document.getElementById('modifyModal').style.display = 'none';
      loadFlights(); // 刷新数据
    } else {
      alert('修改失败');
    }
  });

  // 分页跳转
  document.getElementById('goToPage').addEventListener('click', () => {
    const page = document.getElementById('currentPage').value;
    loadFlights(page);
  });

  // 点击页面其他区域关闭弹窗（修改后）
  document.addEventListener('click', (e) => {
    const modalBackdrop = document.getElementById('modalBackdrop');
    const isClickingModal = e.target.closest('.add-modal'); // 检查是否点击弹窗内部
    const isClickingBackdrop = e.target === modalBackdrop; // 检查是否点击灰幕

    if (!isClickingModal && isClickingBackdrop) { // 仅当点击灰幕且不在弹窗内部时关闭
      document.querySelectorAll('.add-modal').forEach(modal => modal.style.display = 'none');
      modalBackdrop.style.display = 'none';
    }
  });
</script>
</body>
</html>